package com.architecture.core.filter;

import com.architecture.core.entity.BaseEntity;
import org.apache.log4j.Logger;
import org.hibernate.CallbackException;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

/**
 * Created with Aguang
 * LoginAction: Administrator
 * Date: 12-5-8
 * Time: 下午4:47
 * 通过hibernate操作数据库时会回调本类方法。在spring-config.xml中已向hibernate注册了此类
 */
public class DBInterceptor extends EmptyInterceptor {
    protected final Logger logger = Logger.getLogger(this.getClass());

    @Override
    public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
        if (entity instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) entity;
            baseEntity.setCreateTime(new Timestamp(new Date().getTime()));
        }
        return true;
    }

    /**
     * 更新记录时调用
     * @param obj
     * @param key
     * @throws CallbackException
     */
    @Override
    public void onCollectionUpdate(Object obj, Serializable key) throws CallbackException {

        Timestamp currentTime = new Timestamp(new Date().getTime());

        if (obj instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) obj;
            baseEntity.setUpdateTime(currentTime);
        } else if (obj instanceof Collection) {          //如果为批量更新，则批量修改更新时间
            Collection collection = (Collection) obj;
            for (Object cell : collection) {
                if (cell instanceof BaseEntity) {
                    BaseEntity baseEntity = (BaseEntity) cell;
                    baseEntity.setUpdateTime(currentTime);
                }
            }
        }

    }

}
